package com.paiai.lslease.action.appuser;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dsmzg.base.util.http.HttpPost;
import com.paiai.lslease.auto.model.AppMessageCode;
import com.paiai.lslease.auto.model.AppSysUser;
import com.paiai.lslease.base.AppResult;
import com.paiai.lslease.base.BaseAction;
import com.paiai.lslease.base.WChatConstants;
import com.paiai.lslease.model.bo.MobileModifyBo;
import com.paiai.lslease.service.appuser.AppMessageCodeService;
import com.paiai.lslease.service.appuser.AppSysUserService;
import com.paiai.lslease.service.appuser.AppUserModuleService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.SQLException;

/** 
* @author chenmfa
* @version 创建时间：2017年10月19日 下午4:28:21 
* @description 模块我的接口
*/
@SuppressWarnings("serial")
public class AppMineAction extends BaseAction{
  
  private static final Logger logger = LoggerFactory.getLogger(AppMineAction.class);  
  private String mobile;
  private String userShortNum;
  private String wxcode;
  private String account;
  @Autowired
  private AppMessageCodeService appMessageCodeService;
  @Autowired
  private AppSysUserService appSysUserService;
  @Autowired
  AppUserModuleService appUserModuleService;
  /**
   * @description 用户登录
   */
  public void login() {
    AppResult msg;
    long s = System.currentTimeMillis();
    if(StringUtils.isBlank(userShortNum)){
      msg = AppResult.newFailResult("验证码不能为空");
    }else if(StringUtils.isBlank(mobile)){
      msg = AppResult.newFailResult("手机号不能为空");
    }else{  
      AppSysUser loginUser = new AppSysUser();
      try {
        logger.info(request.getRequestURI()+",接收到的参数："+JSON.toJSONString(request.getParameterMap()));
        String result = HttpPost.postByHttpClient(WChatConstants.WCHAT_OPENID_URL+wxcode, null);
        if(null != result){
          try{
            JSONObject json = JSON.parseObject(result);
            if(null == json.getString("openid")){
              if(null != json.getString("errmsg")){
                if(json.getString("errmsg").contains("code been used")){
                  msg = AppResult.newFailResult("凭证已过期");
                }
              }
            }else{
              loginUser.setWechatOpenId(json.getString("openid"));
            }
          }catch(Exception e){
            logger.error("未获取到微信的openid",e);
          }
        }
        if(null == loginUser.getWechatOpenId()){         
          msg = AppResult.newFailResult("未获取到微信的openid");
        }else{
          //开始获取验证码
          AppMessageCode appMessageCode = new AppMessageCode();
          appMessageCode.setUserMobileAccount(mobile);
          appMessageCode.setUserShortNum(userShortNum);
          String checkResult = appMessageCodeService.checkMessageCode(appMessageCode);
          if (!StringUtils.isBlank(checkResult)) {
            msg = AppResult.newFailResult(checkResult);
          }else{
            AppSysUser appSysUser = new AppSysUser();
            appSysUser.setMobile(mobile);
            appSysUser.setWechatOpenId(loginUser.getWechatOpenId());
            appSysUser.setRemark("绑定微信账号");
            //如果验证码通过,则开始登陆(如果用户为注册，则自动注册用户)
            AppSysUser appSysUserInfo = appSysUserService.bindWXAccount(appSysUser);
            if(null != appSysUserInfo){
              msg = AppResult.newSusscessResult("登陆成功",appSysUserInfo);
            }else{
              msg = AppResult.newFailResult("登陆失败");
            }
          }
        }
      } catch (Exception e){
        logger.error("登陆出错",e);
        msg = AppResult.newFailResult("登陆失败");
      }finally{        
        logger.info("登陆操作完成,消耗时间：{}",(System.currentTimeMillis()-s));
      }
    }
    sendResultMsg(msg);
  }
  
  
  public void bindNewPhone(){
    AppResult msg;
    long s = System.currentTimeMillis();
    if(StringUtils.isBlank(userShortNum)){
      msg = AppResult.newFailResult("验证码不能为空");
    }else if(StringUtils.isBlank(mobile)){
      msg = AppResult.newFailResult("手机号不能为空");
    }else if(StringUtils.isBlank(account)){
      msg = AppResult.newFailResult("当前用户不能为空");
    }else{  
      try {
        logger.info(request.getRequestURI()+",接收到的参数："+JSON.toJSONString(request.getParameterMap()));
        //开始获取验证码
        AppMessageCode appMessageCode = new AppMessageCode();
        appMessageCode.setUserMobileAccount(mobile);
        appMessageCode.setUserShortNum(userShortNum);
        String checkResult = appMessageCodeService.checkMessageCode(appMessageCode);
        if (!StringUtils.isBlank(checkResult)) {
          msg = AppResult.newFailResult(checkResult);
        }else{
//          更新用户的手机号码
          MobileModifyBo mmb = new MobileModifyBo();
          mmb.setAccount(account);
          mmb.setMobile(mobile);
          //如果验证码通过,则开始登陆(如果用户为注册，则自动注册用户)
          msg = appUserModuleService.updateUserMobile(mmb);
        }
      } catch (Exception e){
        logger.error("修改密码出错",e);
        msg = AppResult.newFailResult("修改密码失败");
      }finally{        
        logger.info("修改密码操作完成,消耗时间：{}",(System.currentTimeMillis()-s));
      }
    }
    sendResultMsg(msg);
  }
  
  /**
   * @description 查询我的界面的的基础数据
   */
  public void queryMyInfo(){
    AppResult result;
    if(null == mobile){
      result = AppResult.newFailResult("用户手机号不能为空");
    }else{
      try {
        logger.info(request.getRequestURI()+",接收到的参数："+JSON.toJSONString(request.getParameterMap()));
        result = appUserModuleService.queryMyInfo(mobile);
      } catch (SQLException e) {
        logger.error("查询用户信息出错",e);
        result = AppResult.newFailResult("查询用户信息失败");
      }
    }
    sendResultMsg(result);
  }


  public void setMobile(String mobile) {
    this.mobile = mobile;
  }
  public void setUserShortNum(String userShortNum) {
    this.userShortNum = userShortNum;
  }
  public void setWxcode(String wxcode) {
    this.wxcode = wxcode;
  }
  public void setAccount(String account) {
    this.account = account;
  }
}
